package servlet;

import dao.BanTinDao;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import pojo.BanTinPoJo;
import pojo.DanhMucPoJo;
import pojo.KhuVucPoJo;
import pojo.LoaiTinPoJo;
import util.UploaddedFileData;

/**
 *
 * @author Nautilus
 */
public class DangVoucher extends HttpServlet
{
    private static final String TMP_DIR = "D:/temp/web";
    private static final String DES_DIR = "image_chozoi";
    private File tmpDir = null;
    private static File desDir = null;
       
    @Override
    public void init(ServletConfig config)
    {
    	tmpDir = new File(TMP_DIR);
    	if(desDir == null)
    		desDir = new File(config.getServletContext().getRealPath("/" + DES_DIR));
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setRepository(tmpDir);
	ServletFileUpload uploadHandler = new ServletFileUpload(factory);
	uploadHandler.setHeaderEncoding("utf-8"); 
	List<FileItem> items = null;
	List<UploaddedFileData> lstFiles = new ArrayList<UploaddedFileData>(); 
	String fieldName, fieldValue;
        
        try{
            BanTinPoJo bt = new BanTinPoJo();
            bt.setngayDang(new Date());
            
            //System.out.println("[NhapHoaServlet] " + tmpDir.getPath());
			
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			
            if(!isMultipart)
            {
		System.out.println("[NhapHoaServlet] NOT multipart request");
            }
			
			
            items = uploadHandler.parseRequest(request);
			
            for(FileItem item:items)
            {
                fieldName = item.getFieldName();
                if(item.isFormField())
		{	
                    fieldValue = item.getString("UTF-8");
                    
                    if(fieldName.toLowerCase().equals("cbocategory"))
                    {
                        System.out.println("DANH MUC ID: " + fieldName);
                        bt.setDanhMuc(new DanhMucPoJo(Integer.parseInt(fieldValue)));
                    }
					
                    if(fieldName.toLowerCase().equals("cbolocation"))
                        bt.setKhuVuc(new KhuVucPoJo(Integer.parseInt(fieldValue)));
					
                    if(fieldName.toLowerCase().equals("coupon_title"))
                    {
                        System.out.println("Ten hoa: " + fieldValue);
			bt.settieuDe(fieldValue);
                    }
					
                    if(fieldName.toLowerCase().equals("coupon_content"))
                        bt.setnoiDung(fieldValue);
					
                    if(fieldName.toLowerCase().equals("coupon_sales_price"))
                        bt.setGiaBan(Integer.parseInt(fieldValue));
					
                    if(fieldName.toLowerCase().equals("cboexpireddate"))
                    {
                        //System.out.println("Ten hoa: " + fieldValue);
                        int tgian = Integer.parseInt(fieldValue);
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(bt.getngayDang());
                        cal.add(Calendar.DATE, tgian);
                        bt.setngayHetHan(cal.getTime());
                    }	
		}
		else
		{
                    UploaddedFileData ufd = new UploaddedFileData(item.getInputStream(), item.getName());
                    lstFiles.add(ufd);
		}
            }
            
            LuuFileHinh(bt, lstFiles, desDir);
	}catch(FileUploadException ex) 
	{
            ex.printStackTrace();
            log("Error encountered while parsing the request",ex);
	} catch(Exception ex) 
	{
            ex.printStackTrace();
            log("Error encountered while uploading file",ex);
	}
        
        String preUrl = "/index.jsp";
	RequestDispatcher dispatcher = request.getRequestDispatcher(preUrl);
	dispatcher.forward(request, response);
        
    }
    
    public boolean LuuFileHinh(BanTinPoJo bt, List<UploaddedFileData> items, File desDir)
    {
	String hinh = "";
        int id = 0;
        try{
            BanTinDao dao = new BanTinDao();
            bt.setLoaiTin(new LoaiTinPoJo(1));
            
            if(bt.getidBanTin()<=0)
                dao.ThemBanTin(bt);
                
            id = bt.getidBanTin();
            
            try {
                hinh = "img_"+id + items.get(0).getExtension();
                //System.out.println(hinh);
                File file = new File(desDir,hinh);
                System.out.println(file);
                items.get(0).writeFile(file);
            } catch (IOException e)
            {
                e.printStackTrace();
		return false;	
            }
            bt.setHinhAnh(hinh);
            dao.CapNhatBanTin(bt);
            return true;
	}catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }
    
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
